<template>
    <div class="app-container">
        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
            <el-input placeholder="请输入用户名" v-model="searchParam.SEARCH_LIKE_user_name" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-input placeholder="请输入手机号" v-model="searchParam.SEARCH_EQ_mobile" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
            <el-button class="filter-item" type="default" icon="el-icon-search" @click="searchReset"> 重置</el-button>
<!--            <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate"> 新增</el-button>-->
            <el-button class="filter-item" type="default" icon="el-icon-download" @click="handleExport">导出用户列表
            </el-button>
        </div>

        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
                  style="width: 100%;">
            <el-table-column v-for="column in columns" :key="column.prop"
                             :prop="column.prop"
                             :label="column.label"
                             :width="column.width"
                             :align="column.align?column.align:'center'"
                             :min-width="column.minWidth"
                             :sortable="column.sortable"
                             :fixed="column.fixed"
                             :type="column.type" :formatter="column.formatter">
                <template slot-scope="scope">
                    <!-- 行内显示图片 -->
                    <img v-if="column.imgFlag===true"
                         :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                         width="60" height="60" class="img" alt=""/>
                    <!-- 行内显示开关按钮 -->
                    <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                               :inactive-value="0" disabled/>
                    <!-- 行内显示tag标签 -->
                    <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
                    <!-- 行内格式自定义 -->
                    <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                    <!--默认显示文本-->
                    <span v-else>{{ scope.row[column.prop] }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> 查看</el-button>
                    <el-button type="primary" size="mini" @click="inviteToBeAnchor(scope.row)"> 邀请成为主播</el-button>
                    <el-button type="primary" size="mini" @click="addLable(scope.row)"> 添加标签</el-button>
<!--                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)"> 删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <!-- 表格-页脚区域 -->
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                    :limit.sync="pageRequest.pageSize" @pagination="getList"/>

        <!--新增编辑界面-->
        <el-dialog :title="operation?'新增':'查看'" width="45%" top="5vh" :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false">
            <el-form ref="dataForm" :model="dataForm" :rules="dataFormRules" disabled label-width="140px" style="width: 80%">

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="dataForm.mobile" auto-complete="off" placeholder="请输入手机号"/>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="dataForm.password" auto-complete="off" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item label="头像" prop="headImg">
                    <cm-upload v-model="dataForm.headImg"></cm-upload>
                </el-form-item>
                <el-form-item label="人生格言" prop="signature">
                    <el-input v-model="dataForm.signature" auto-complete="off" placeholder="请输入人生格言"/>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="dataForm.age" auto-complete="off" placeholder="请输入年龄"/>
                </el-form-item>
                <el-form-item label="擅长项目" prop="speciality">
                    <el-input v-model="dataForm.speciality" auto-complete="off" placeholder="请输入擅长项目"/>
                </el-form-item>
                <el-form-item label="是否展示成绩" prop="isShowGrade">
                    <el-switch v-model="dataForm.isShowGrade" :active-value="1"
                               :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="用户标签" prop="userLabelValue">
                    <el-input v-model="this.userLabelValue" auto-complete="off" placeholder="请输入用户标签"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialog()">取消</el-button>
                <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :title="'添加标签'" width="45%" top="5vh" :visible.sync="dialogLabelFormVisible"
                   :close-on-click-modal="false">
            <el-form ref="dataLabelForm" :model="dataLabelForm" :rules="dataLabelFormRules"  label-width="140px" style="width: 80%">
                <el-form-item label="标签内容" prop="label">
                    <el-input v-model="dataLabelForm.label" auto-complete="off" placeholder="请输入标签内容"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeLabelDialog()">取消</el-button>
                <el-button size="mini" @click.native="saveLabelFormData()" :loading="editLoading" type="primary">提交
                </el-button>
            </div>
        </el-dialog>


    </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import {
    adminWithdrawCheck,
    deleteJdAppUser,
    editJdAppUser,
    getJdAppUserList,
    saveJdAppUser,
    inviteToBeAnchorById,
    saveJdLabelSend,
    editJdLabelSend,
    getUserLabelList,
    getExportList
} from '@/api/modules/appUser'
import CmUpload from '@/components/Upload' // 上传图片组件引入
import table2excel from 'js-table2excel'
import {deleteMenu} from "@/api/modules/cm-system";

export default {
    name: 'appUser',
    components: {
        Pagination,
        CmUpload,
    },
    directives: {},
    filters: {
    },
    data() {
        return {
            tableKey: 0,
            tableList: [],//表格数据源
            exprotTableList: [],//导出表格数据源
            tableTotal: 0,//表格总条数数据
            listLoading: true,
            pageRequest: {pageNum: 1, pageSize: 10,},
            searchParam: {},
            dialogFormVisible: false,//默认不显示弹出框
            dialogLabelFormVisible: false,//默认不显示弹出框
            operation: true, // true:新增, false:编辑
            editLoading: false,//保存表单时loading框
            columns: [
                // {prop: 'id',  label: '',  sortable:false  },
                {prop: 'userNum', label: '用户编号', sortable: false},
                {prop: 'mobile', label: '手机号', sortable: false},
                // {prop: 'password',  label: '密码',  sortable:false  },
                // {prop: 'salt',  label: '盐值',  sortable:false  },
                {prop: 'headImg', label: '头像', sortable: false, imgFlag: true},
                {prop: 'userName', label: '用户名', sortable: false},
                {prop: 'signature', label: '人生格言', sortable: false},
                // {prop: 'lastLoginTime',  label: '上次登录时间',  sortable:false  },
                // {prop: 'role',  label: '角色',  sortable:false  },
                // {prop: 'wxUnionId',  label: '微信unionid',  sortable:false  },
                {prop: 'age', label: '年龄', sortable: false},
                {prop: 'speciality', label: '擅长项目', sortable: false},
                {prop: 'isShowGrade', label: '是否展示成绩', sortable: false, switchFlag: true,},
                // {prop: 'parentId', label: '所属第三方机构', sortable: false},
                {prop: 'appVersion', label: '版本号', sortable: false},
                {
                    prop: 'deviceModel', label: '1安卓2ios', sortable: false, tagFlag: true,
                    tagFormatter: [
                        {text: '安卓', value: 1, type: 'success'},
                        {text: 'ios', value: 2, type: 'warn'},
                    ]
                },
                {prop: 'inviteCode', label: '邀请人手机号', sortable: false},

                // {prop: 'registerTime',  label: '注册时间',  sortable:false  },
            ],
            fileList: [],
            // 新增编辑界面数据
            dataForm: {
            },
            dataLabelForm: {},
            //表单检验规则
            dataFormRules: {
                id: [{required: true, message: '请输入', trigger: 'blur'}],
                userNum: [{required: true, message: '请输入用户编号', trigger: 'blur'}],
                mobile: [{required: true, message: '请输入手机号', trigger: 'blur'}],
                password: [{required: true, message: '请输入密码', trigger: 'blur'}],
                salt: [{required: true, message: '请输入盐值', trigger: 'blur'}],
                headImg: [{required: true, message: '请输入头像', trigger: 'blur'}],
                userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                signature: [{required: true, message: '请输入人生格言', trigger: 'blur'}],
                lastLoginTime: [{required: true, message: '请输入上次登录时间', trigger: 'blur'}],
                role: [{required: true, message: '请输入角色', trigger: 'blur'}],
                // wxUnionId: [ { required: true, message: '请输入微信unionid', trigger: 'blur' } ],
                age: [{required: true, message: '请输入年龄', trigger: 'blur'}],
                speciality: [{required: true, message: '请输入擅长项目', trigger: 'blur'}],
                isShowGrade: [{required: true, message: '请输入是否展示成绩0不是1是', trigger: 'blur'}],
                parentId: [{required: true, message: '请输入所属第三方机构', trigger: 'blur'}],
                appVersion: [{required: true, message: '请输入版本号', trigger: 'blur'}],
                deviceModel: [{required: true, message: '请输入1安卓2ios', trigger: 'blur'}],
                registerTime: [{required: true, message: '请输入注册时间', trigger: 'blur'}],
            },
            dataLabelFormRules: {
                label: [{required: true, message: '请输入标签', trigger: 'blur'}],
            },
            userLabelValue:''
        }
    },
    methods: {
        //获取表格数据
        getList() {
            this.listLoading = true
            //【API请求】----获取表格列表数据
            getJdAppUserList(this.pageRequest).then(response => {
                response = response.result
                this.tableList = response.list
                this.tableTotal = response.total
                this.listLoading = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getExportList() {
            //【API请求】----获取表格列表数据
            getExportList(this.pageRequest).then(response => {
                response = response.result
                this.exprotTableList = response
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //表格数据筛选
        handleFilter() {
            this.pageRequest.searchParam = this.searchParam
            this.getList()
            this.getExportList()

        },
        //【按钮点击】--- 弹出新增表单
        handleCreate() {
            this.operation = true;
            this.initDataForm();
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //【按钮点击】--- 弹出编辑表单
        handleUpdate(row) {
            this.operation = false;
            this.dataForm.deviceModel = this.dataForm.deviceModel + ""
            //获取用户标签
            this.getLabel(row.id)
            this.dataForm = Object.assign({}, row)
            // console.log("this.dataForm",this.dataForm)
            // console.log("this.dataForm.age",this.dataForm.age)
            // console.log("this.dataForm.userLabelValue",this.dataForm.userLabelValue)
            // this.dataForm.userLabelValue = "1"
            //显示编辑菜单
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //[用户标签]---获取用户标签
        getLabel(userId){
            //【API请求】----获取用户标签列表
            const params = {
                "getUser":userId
            }
            getUserLabelList(params).then(response => {
                this.userLabelValue = response.result
                console.log("userLabelValue",this.userLabelValue)
                // this.dataForm.userLabelValue = 1;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //保存表单数据
        saveFormData() {
            let res
            this.$refs['dataForm'].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoading = true;
                //【API请求】----保存数据
                // console.log(this.dataForm);
                if (this.dataForm.id === null || this.dataForm.id === '') {
                    const params = {
                        mobile: this.dataForm.mobile,
                        password: this.dataForm.password,
                        headImg: this.dataForm.headImg,
                        signature: this.dataForm.signature,
                        lastLoginTime: this.dataForm.lastLoginTime,
                        role: this.dataForm.role,
                        wxUnionId: this.dataForm.wxUnionId,
                        age: this.dataForm.age,
                        speciality: this.dataForm.speciality,
                        isShowGrade: this.dataForm.isShowGrade,
                        parentId: this.dataForm.parentId,
                        appVersion: this.dataForm.appVersion,
                        deviceModel: this.dataForm.deviceModel,
                        registerTime: this.dataForm.registerTime,
                    }
                    res = await saveJdAppUser(params)
                } else {
                    res = await editJdAppUser(this.dataForm)
                }
                try {
                    if (res.code === 0) {
                        this.dialogFormVisible = false// 关闭表单页面
                        this.initDataForm()// 重置表单数据
                        this.getList()// 重新获取表格数据
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoading = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        //【按钮点击】---添加标签
        addLable(row){
            this.dialogLabelFormVisible = true
            this.dataLabelForm.getUser = row.id;
        },
        //保存添加标签表单数据
        saveLabelFormData() {
            let res
            this.$refs['dataLabelForm'].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoading = true;
                //【API请求】----保存数据
                // console.log(this.dataForm);
                // if (this.dataLabelForm.id === null || this.dataLabelForm.id === '') {
                //     const params = {
                //         label: this.dataLabelForm.label,
                //         getUser: this.dataLabelForm.getUser,
                //     }
                //     res = await editJdLabelSend(params)
                // } else {
                    res = await saveJdLabelSend(this.dataLabelForm)
                // }
                try {
                    if (res.code === 0) {
                        this.dialogLabelFormVisible = false// 关闭表单页面
                        this.initLabelDataForm()// 重置表单数据
                        this.getList()// 重新获取表格数据
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoading = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        //【按钮点击】---删除行
        handleDelete(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                //【API请求】---- 删除数据
                deleteJdAppUser(row.id).then(() => {
                    this.$message({message: '操作成功', type: 'success'})
                    this.getList();
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            });
        },
        //【按钮点击】---邀请成为主播主播
        inviteToBeAnchor(row){
            this.$confirm('确认邀请成为主播吗？', '提示', {}).then(() => {
                const params = {
                    userId: row.id,
                }
                inviteToBeAnchorById(params).then(response => {
                    console.log("response",response);
                    if(response.code == 500){
                        this.$message({ message: response.message, type: 'error' })
                        this.getList()
                    }else{
                        this.$message({ message: response.message, type: 'success' })
                        this.getList()
                    }
                }).catch(() => {
                    this.$message({message: '邀请失败', type: 'error'})
                })
            }).catch(() => {
                this.$message({message: '邀请失败', type: 'error'})
            })
        },

        handleExport() {
            this.$confirm('确认导出用户数据吗？', '提示', {}).then(() => {
                //用户数据list
                this.list = this.exprotTableList
                // console.log(this.list);
                this.listLoading = false
                // 将this.list中的数据导出
                const column = [
                    {title: '用户编号', key: 'userNum', type: 'text'},
                    {title: '手机号', key: 'mobile', type: 'text'},
                    {title: '头像', key: 'headImg', type: 'image', width: 60, height: 60},
                    {title: '用户名', key: 'userName', type: 'text'},
                    {title: '人生格言', key: 'signature', type: 'text'},
                    {title: '年龄', key: 'age', type: 'text'},
                    {title: '擅长项目', key: 'speciality', type: 'text'},
                    {title: '所属第三方机构', key: 'parentId', type: 'text'},
                    {title: '版本号', key: 'appVersion', type: 'text'},
                    {title: '设备型号', key: 'deviceModel', type: 'text'},
                    {title: '注册时间', key: 'registerTime', type: 'text'},
                ]
                //不需要导出的字段
                const unExport = [
                    'id',
                    'isShowGrade',
                    'lastLoginTime',
                    'password',
                    'role',
                    'salt',
                    'wxUnionId',
                ]
                debugger;
                const data = this.formatJson(unExport, this.list.map(item => {
                        item.deviceModel = this.formatDeviceModel(item)
                        item.headImg = this.CMBASE.baseFileContext + item.headImg
                        return item
                    })
                )
                const excelName = '用户数据'
                table2excel(column, data, excelName)
            }).catch((res) => {
                console.log(res);
            })
        },
        formatJson(unExport, jsonData) {
            let j = JSON.parse(JSON.stringify(jsonData))
            j.map(v => {
                unExport.forEach(item => {
                    this.$delete(v, item)
                })
            })
            return j
        },
        formatDeviceModel(row) {
            if (row.deviceModel === 1) {
                return '安卓'
            } else {
                return 'ios'
            }
        },
        // 重置按钮
        searchReset() {
            this.searchParam = {}
            this.pageRequest = {pageNum: 1, pageSize: 10}
            this.getList()
            this.getExportList()

        },
        //初始化表单数据，重新渲染
        initDataForm() {
            this.dataForm = {
                id: '',
                userNum: '',
                mobile: '',
                password: '',
                salt: '',
                headImg: '',
                userName: '',
                signature: '',
                lastLoginTime: '',
                role: '',
                wxUnionId: '',
                age: '',
                speciality: '',
                isShowGrade: '',
                parentId: '',
                appVersion: '',
                deviceModel: '',
                registerTime: '',
            };
        },
        initLabelDataForm() {
            this.dataLabelForm = {
                id: '',
                label: '',
                referUser: '',
                getUser: '',
            };
        },
        //关闭表单弹出框
        closeDialog() {
            this.$refs['dataForm'].resetFields();
            this.dialogFormVisible = false
        },
        //关闭表单弹出框
        closeLabelDialog() {
            this.$refs['dataLabelForm'].resetFields();
            this.dialogLabelFormVisible = false
        },

    },
    created() {
        this.getList();
        this.getExportList();
    },
}
</script>
